package org.utils{
	import flash.desktop.Updater;
	import flash.display.*;
	import flash.errors.*;
	import flash.events.*;
	import flash.filesystem.*;
	import flash.net.*;
	import flash.text.TextField;
	import flash.utils.ByteArray;
	import flash.xml.*;
	
	import mx.controls.Alert;
	import mx.core.UIComponent;
	import mx.flash.UIMovieClip;
	
	import org.net.*;

	public class AIRUpdater extends UIMovieClip {
		
		public var version:String="beat1";
		
		public var updataURL:String="http://www.wakao123.com/AbcFrame.xml";
		
		var updater:Updater
		
		var urlStream:URLStream
		
		var fileData:ByteArray
		
		var newVersion:String

		public function AIRUpdater():void {
			
			loadxml()
			
		}
		
		function loadxml(){
			
			var res:AbcResponder=new AbcResponder()
			
			res.onResult=function(e,path){
				
				trace(e,path)
				
				var data:XML=XML(e)
					
				trace(data.version,version)	
					
				if(data.version==version){return;}
				
				
				
				newVersion=data.version
				
				loadAir(data.lastpublic)
				
			}
			
			res.onFault=function(e,path){
				
				trace(e,path)
				
			}

			new AbcHTTPServices(updataURL,res)
			
		}
		
		
		function loadAir(airurl:String){
					
			var urlReq:URLRequest=new URLRequest(airurl);
			
			urlStream=new URLStream() ;
			
			fileData=new ByteArray() ;
			
			urlStream.addEventListener(Event.COMPLETE,loaded);
			
			urlStream.addEventListener(IOErrorEvent.IO_ERROR ,function(e:IOErrorEvent){Alert.show("自动更新出错了！")});
			
			urlStream.load(urlReq);
		
		}
		
		private function loaded(event:Event):void {
			
			urlStream.readBytes(fileData,0,urlStream.bytesAvailable);
			writeAirFile();
		}
		
		private function writeAirFile():void {
			var file:File=File.desktopDirectory.resolvePath("AbcFrame.air");
			var fileStream:FileStream=new FileStream ;
			fileStream.addEventListener(Event.CLOSE,fileClosed);
			fileStream.openAsync(file,FileMode.WRITE);
			fileStream.writeBytes(fileData,0,fileData.length);
			fileStream.close();
		}
		
		private function fileClosed(event:Event):void {
			trace("The AIR file is written.");
			var updater:Updater=new Updater ;
			var airFile:File=File.desktopDirectory.resolvePath("AbcFrame.air");
			updater.update(airFile,newVersion);
		}
	}
}

